<?php
/**
* images Class
*/

class images
extends entity
{
	/**
	* Optional Constructor: Load on demand only.
	*/
	public function __construct()
	{
		# Parent's default constructor is necessary.
		parent::__construct();

		/**
		* Set Private, Protected or Public Members
		*/
		$this->protection_code = 'f4322490e40d1e61cf8840b297675702'; # Some random text, valid for the entire life
		$this->table_name = 'gallery_images'; # Name of this table/entity name
		$this->pk_column = 'image_id'; # Primary Key's Column Name

		/**
		* Validation fields as used in add/edit forms
		*/
		$this->fields = array(
			# Remove the columns that you do not want to use in the ADD form
			'add' => array(
				'dimension_width' => null,
				'dimension_height' => null,
				'filesize_bytes' => null,
				'image_code' => null,
				'image_name' => null,
				'image_caption' => null,
				'image_keywords' => null,
				'image_description' => null,
				
				'image_mime' => null,
			),
			
			# Remove the columns that you do not want to use in the EDIT form
			'edit' => array(
				'dimension_width' => null,
				'dimension_height' => null,
				'filesize_bytes' => null,
				'image_code' => null,
				'image_name' => null,
				'image_caption' => null,
				'image_keywords' => null,
				'image_description' => null,
				
				'image_mime' => null,
			),
		);
	}

	/**
	* List entries from [ images ]
	* Column `code` signifies a protection code while deleting/editing a record
	* @param $conditions SQL Conditions
	* @return Multi-Dimensional array of entries in the list
	*/
	public function list_entries(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.impressions_counter,
	
	e.is_approved,
	e.is_featured,
	e.is_finished,
	e.in_bannerimage,
	
	MD5(CONCAT(`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	`sink_weight` ASC,
	`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	/**
	* List entries from [ images ]
	* Column `code` signifies a protection code while deleting/editing a record
	* @param $conditions SQL Conditions
	* @return Multi-Dimensional array of entries in the list
	*/
	public function list_valid_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ia ON ia.image_id = e.image_id AND ia.is_active='Y' AND ia.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id=ia.album_id AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	e.`sink_weight` ASC,
	e.`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	/**
	* List out most popular images
	*/
	public function list_popular_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ia ON ia.image_id = e.image_id AND ia.is_active='Y' AND ia.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id=ia.album_id AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	e.`impressions_counter` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	/**
	* Details of an entity in [ images ] for management activities only.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function details($image_id=0)
	{
		global $subdomain_id;
		$image_id = (int)$image_id;
		$details_sql="
SELECT
	e.`image_id`, # Do not remove this

	e.*, # Modify these columns,
	
	# Admin must have it to EDIT the records
	MD5(CONCAT(`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
WHERE
	`image_id` = {$image_id}
	# AND subdomain_id={$subdomain_id}
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Details of an entity in [ images ] for public display.
	* @param $pk integer Primary Key's value of an entity
	* @return $details Associative Array of Detailed records of an entity
	*/
	public function get_details($image_id=0, $protection_code='')
	{
		$protection_code = $this->sanitize($protection_code);
		$image_id = (int)$image_id;
		$details_sql="
SELECT
	`image_id`, # Do not remove this

	e.*, # Modify these columns

	MD5(CONCAT(`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
WHERE
	`image_id` = {$image_id}
	AND e.is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(`image_id`, '{$this->protection_code}')) = '{$protection_code}'
;";
		$details = $this->row($details_sql);
		return $details;
	}

	/**
	* Flag a field; dummy use; unless you use it.
	* Every method should sanitize the user input.
	* It will co-exist with the live features.
	*/
	public function flag_field($image_id=0, $protection_code='', $field_name='')
	{
		# Allow only selected fields to be flaged Y/N
		if(!in_array($field_name, array('is_approved', 'is_featured', 'is_finished', 'in_bannerimage')))
		{
			# Such flag does not exist.
			return false;
		}
		
		$image_id = (int)$image_id;
		$protection_code = $this->sanitize($protection_code);
		global $subdomain_id;
		
		$additional_flags_dml = '';
		switch($field_name)
		{
		case 'is_featured':
			$additional_flags_dml = ", featured_on=UNIX_TIMESTAMP(CURRENT_TIMESTAMP())";
			break;
		}

		$flag_sql="
UPDATE `{$this->table_name}` SET
	# Set your flag name here
	modified_on=UNIX_TIMESTAMP(CURRENT_TIMESTAMP()),
	`{$field_name}`=IF(`{$field_name}`='Y', 'N', 'Y')
	{$additional_flags_dml}
WHERE
	`image_id` = {$image_id}
	AND subdomain_id={$subdomain_id}
	
	# Don't touch the deleted flags
	AND is_active='Y'

	# Optionally validate
	AND MD5(CONCAT(`image_id`, '{$this->protection_code}')) = '{$protection_code}'
;";
		return $this->query($flag_sql);
	}

	/**
	* Welcome and ask for authentication?
	* Please extend this method according to your business logic.
	* Used right after a new images is added.
	*/
	public function welcome_first($image_id=0)
	{
		$image_id = (int)$image_id;
	 	
		return true;
	}
	
	
	
	/**
	* Draws recently modified images
	*/
	public function list_recently_modified_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.is_approved,
	e.is_featured,
	e.in_bannerimage,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ai ON ai.image_id = e.image_id AND e.is_active='Y' AND e.is_approved='Y' AND ai.is_approved='Y' AND ai.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id = ai.album_id AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# e.`approved_on` DESC, # Also use this flag
	e.`modified_on` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	/**
	* Draws images featured by the publishers
	*/
	public function list_featured_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.is_approved,
	e.is_featured,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ai ON ai.image_id = e.image_id AND e.is_active='Y' AND e.is_approved='Y' AND ai.is_approved='Y' AND ai.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id = ai.album_id AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	e.`featured_on` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	/**
	* Lists images within particular album
	*/
	public function list_album_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.is_approved,
	e.is_featured,
	e.is_finished,
	e.impressions_counter,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ai ON ai.image_id = e.image_id AND e.is_active='Y' AND e.is_approved='Y' AND ai.is_approved='Y' AND ai.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id = ai.album_id AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	e.`sink_weight` ASC,
	e.`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	/**
	* Lists images within particular album - for the admin purpose only
	*/
	public function list_album_images_admin(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.is_approved,
	e.is_featured,
	e.is_finished,
	e.in_bannerimage,
	e.impressions_counter,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ai ON ai.image_id = e.image_id
	# AND e.is_active='Y' AND e.is_approved='Y' AND ai.is_approved='Y' AND ai.is_approved='Y'
INNER JOIN gallery_albums a ON a.album_id = ai.album_id
	# AND a.is_active='Y' AND a.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	e.`sink_weight` ASC,
	e.`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	
	/**
	* Lists images with certain tags
	*/
	public function list_taged_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	e.is_approved,
	e.is_featured,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_tags it ON it.image_id = e.image_id AND e.is_active='Y' AND e.is_approved='Y' AND it.is_approved='Y' AND it.is_approved='Y'
INNER JOIN gallery_tags t ON t.tag_id = it.tag_id AND t.is_active='Y' AND t.is_approved='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	e.`sink_weight` ASC,
	e.`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	
	/**
	* Lists images with certain categories
	*/
	public function list_category_images(condition $condition, $from_index=0, $per_page=50)
	{
		$crud = new crud();

		/**
		* Conditions are Compiled here so that we can manupulate them individually.
		* And make them fit for [ images ] only.
		*/
		$conditions_compiled_AND = $crud->compile_conditions(
			$condition->get_condition('AND'),
			false, 'AND', 1
		);
		$conditions_compiled_OR = $crud->compile_conditions(
			$condition->get_condition('OR'),
			false, 'OR', 2
		);

		$from_index = (int)$from_index;
		$per_page   = (int)$per_page;
		$variable   = new variable(); # It may be necessary to read list out data of a user

		$listing_sql="
SELECT SQL_CALC_FOUND_ROWS
	e.`image_id`, # Do not remove this
	
	# Modify these columns to your own list(e.*)
	e.`dimension_width`,
	e.`dimension_height`,
	e.`filesize_bytes`,
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`,
	e.`image_keywords`,
	e.image_description_short,
	
	MD5(CONCAT(e.`image_id`, '{$this->protection_code}')) `code` # Protection Code
FROM `gallery_images` `e`
INNER JOIN gallery_images_categories `at` ON `at`.image_id = e.image_id AND e.is_active='Y'
INNER JOIN gallery_categories c ON c.category_id = `at`.category_id AND c.is_active='Y'
WHERE
	(
		{$conditions_compiled_AND}
	)
	AND (
		{$conditions_compiled_OR}
	)
ORDER BY
	# We assume that the sorting fields are available
	e.`sink_weight` ASC,
	e.`image_id` DESC
LIMIT {$from_index}, {$per_page}
;";
		#die($listing_sql);
		$this->query($listing_sql);
		$entries = $this->to_array();

		# Pagination helper: Set the number of entries
		$counter_sql="SELECT FOUND_ROWS() total;"; # Uses SQL_CALC_FOUND_ROWS from above query. So, run it immediately.
		$totals = $this->row($counter_sql);
		$this->total_entries_for_pagination = $totals['total'];

		return $entries;
	}
	
	/**
	* List out images that appear in the banners
	*/
	public function get_banner_images()
	{
		$banner_images_sql="
SELECT
	a.album_id,
	e.`image_id`, # Do not remove this
	e.`image_code`,
	e.`image_name`,
	e.`image_caption`
FROM `gallery_images` `e`
INNER JOIN gallery_images_albums ai ON ai.image_id = e.image_id
INNER JOIN gallery_albums a ON a.album_id = ai.album_id
WHERE
	e.is_active='Y' AND e.is_approved='Y' AND e.in_bannerimage='Y'
	AND ai.is_approved='Y' AND ai.is_approved='Y'
	AND a.is_active='Y' AND a.is_approved='Y'
ORDER BY
	e.`modified_on` DESC,
	#e.`sink_weight` ASC
	e.image_id DESC
LIMIT
	10
;";
		$entries = $this->arrays($banner_images_sql);
		return $entries;
	}
	
	/**
	* Re-assign categories, dropping old ones
	* If $categories parameter is empty, it will just remove all the previously assigned categories from the database
	* @rerurn Number of categories assigned
	*/
	public function categories_reassign($image_id=0, $categories=array())
	{
		print_r(func_get_args());
		$image_id = (int)$image_id;
		if(!$image_id) return false;
		
		global $subdomain_id;
		
		# Remove old assigned categories
		$remove_old_categories_sql="DELETE FROM gallery_images_categories WHERE image_id={$image_id}";
		$this->query($remove_old_categories_sql);
		
		# Completely re-assign the new categories
		$counter = 0;
		foreach($categories as $category_id)
		{
			if($category_id = (int)$category_id)
			{
				++$counter;
				$assign_category_sql="
INSERT INTO gallery_images_categories (
	subdomain_id, added_on, is_active,
	image_id, category_id
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y',
	{$image_id}, {$category_id}
);";
				echo $assign_category_sql;
				$this->query($assign_category_sql);
			}
		}
		return $counter;
	}
	
	
	/**
	* Re-assign colors, dropping old ones
	* If $colors parameter is empty, it will just remove all the previously assigned colors from the database
	* @rerurn Number of colors assigned
	*/
	public function colors_reassign($image_id=0, $colors=array())
	{
		print_r(func_get_args());
		$image_id = (int)$image_id;
		if(!$image_id) return false;
		
		global $subdomain_id;
		
		# Remove old assigned colors
		$remove_old_colors_sql="DELETE FROM gallery_images_colors WHERE image_id={$image_id}";
		$this->query($remove_old_colors_sql);
		
		# Completely re-assign the new colors
		$counter = 0;
		foreach($colors as $color_id)
		{
			if($color_id = (int)$color_id)
			{
				++$counter;
				$assign_color_sql="
INSERT INTO gallery_images_colors (
	subdomain_id, added_on, is_active,
	image_id, color_id
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y',
	{$image_id}, {$color_id}
);";
				echo $assign_color_sql;
				$this->query($assign_color_sql);
			}
		}
		return $counter;
	}
	
	
	/**
	* Re-assign sizes, dropping old ones
	* If $sizes parameter is empty, it will just remove all the previously assigned sizes from the database
	* @rerurn Number of sizes assigned
	*/
	public function sizes_reassign($image_id=0, $sizes=array())
	{
		#print_r(func_get_args());
		$image_id = (int)$image_id;
		if(!$image_id) return false;
		
		global $subdomain_id;
		
		# Remove old assigned sizes
		$remove_old_sizes_sql="DELETE FROM gallery_images_sizes WHERE image_id={$image_id}";
		$this->query($remove_old_sizes_sql);
		
		# Completely re-assign the new sizes
		$counter = 0;
		foreach($sizes as $size_id)
		{
			if($size_id = (int)$size_id)
			{
				++$counter;
				$assign_size_sql="
INSERT INTO gallery_images_sizes (
	subdomain_id, added_on, is_active,
	image_id, size_id,
	image_exifinfo
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y',
	{$image_id}, {$size_id},
	''
);";
				#echo $assign_size_sql; die;
				$this->query($assign_size_sql);
			}
		}
		return $counter;
	}
	
	
	/**
	* List of assigned categories of an image
	*/
	public function assigned_categories($image_id=0)
	{
		$image_id = (int)$image_id;
		$sql="SELECT category_id FROM gallery_images_categories WHERE image_id={$image_id};";
		$this->query($sql);
		$ids = $this->to_association('category_id', 'category_id');
		return $ids;
	}

	/**
	* List of assigned categories of an image
	*/
	public function assigned_colors($image_id=0)
	{
		$image_id = (int)$image_id;
		$sql="SELECT color_id FROM gallery_images_colors WHERE image_id={$image_id};";
		$this->query($sql);
		$ids = $this->to_association('color_id', 'color_id');
		return $ids;
	}
	
	/**
	* List of assigned sizes of an image
	* @return array Array of image sizes assigned
	*/
	public function assigned_sizes($image_id=0)
	{
		$image_id = (int)$image_id;
		$sql="SELECT size_id FROM gallery_images_sizes WHERE image_id={$image_id} AND is_active='Y' GROUP BY size_id;";
		$this->query($sql);
		$ids = $this->to_association('size_id', 'size_id');
		return $ids;
	}
	
	/**
	* Upload and newly assign an image to an album
	* @called by - images-upload.php
	*/
	public function upload_image($album_id=0, $image_name='', $filesize_bytes=0, $hash='', $full_path='', $mime='')
	{
		$album_id = (int)$album_id;
		$filesize_bytes = (int)$filesize_bytes;
		$mime = tools::sanitize($mime);
		global $subdomain_id;
		
		# Now, keep the records
		# Add image
		# Assign to album
/*
		$image_sql="
INSERT INTO gallery_images (
	subdomain_id, is_active,
	filesize_bytes, image_code, image_name, image_hash, image_caption, image_keywords, image_description
) VALUES (
	{$subdomain_id}, 'Y',
	{$filesize_bytes}, '{$image_name}', '{$image_name}', '{$hash}', '', '', ''
);";
		$this->query($image_sql);
		$image_id = $this->insert_id();
		
		$album_image_sql="
INSERT INTO gallery_images_albums (
	subdomain_id, added_on, is_active, image_id, album_id
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y',
	{$image_id}, {$album_id}
);";
		$this->query($album_image_sql);
		
		# Store the size information
		
		
*/
		
		
		
		
		$category_id = DEFAULT_CATEGORY_ID; # 0; # Unknown by default
		#chdir($this->album_folder);
		
		# INSERT INTO ...
		# save other info, exif, dimensions, colors, sizes, ...
		# create thumbs (resize), small pic, medium pic, large pic
		# move original pic to its own folder - for original file download purpose
		#$image_id = mt_rand(1000, 9999);
		
		$image_file = $image_name; # addslashes($this->valid_name($image_name));
		
		#$full_path = "{$this->album_folder}/{$image_file}";
		#die($full_path);
		if(!is_file($full_path)) return null;
		
		$filesize_bytes = filesize($full_path);
		$image_code = tools::unique_code();
		$image_hash = sha1_file($full_path);
		
		$info = array();
		$image_sizes = getimagesize($full_path, $info);
		$dimension_width = isset($image_sizes[0])?(int)$image_sizes[0]:0;
		$dimension_height = isset($image_sizes[1])?(int)$image_sizes[1]:0;
		
		$insert_image_sql="
INSERT INTO gallery_images (
	subdomain_id, added_on, is_active, is_approved, is_uploaded,
	dimension_width, dimension_height, filesize_bytes,
	image_code, image_mime,
	image_name, image_caption, image_keywords, image_hash,
	image_description
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y', 'Y', 'Y',
	{$dimension_width}, {$dimension_height}, {$filesize_bytes},
	'{$image_code}', '{$mime}',
	'{$image_file}', '', '', '{$image_hash}',
	''
);";
		#die($insert_image_sql);
		$this->query($insert_image_sql);
		if($image_id = $this->insert_id())
		{
			# Add image sizes
			# Add as default image size for later modifications
			$size_id = THUMBNAIL_ORIGINAL_SIZE_ID;
			$image_mime = exif_imagetype($full_path);
			$image_exifinfo = ''; # addslashes(serialize(exif_read_data($full_path)));
			#print_r(exif_read_data($full_path)); die();

			$automatic_scanned_size_sql="
INSERT INTO gallery_images_sizes (
	subdomain_id, added_on, is_active,
	image_id, size_id, image_filesize,
	image_name, image_name_local, image_hash,
	image_mime, image_exifinfo
) VALUES (
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y',
	{$image_id}, {$size_id}, {$filesize_bytes},
	'{$full_path}', '', '{$image_hash}',
	'{$image_mime}', '{$image_exifinfo}'
);";
			#die($automatic_scanned_size_sql);
			$this->query($automatic_scanned_size_sql);
			
			
			# Also, assign the image to the album
			$album_assign_sql="INSERT INTO gallery_images_albums (subdomain_id, added_on, is_active, is_approved, image_id, album_id) VALUES ({$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y', 'Y', {$image_id}, {$album_id});";
			$this->query($album_assign_sql);
			
			# Mark as unknown category
			$album_assign_sql="INSERT INTO gallery_images_categories (subdomain_id, added_on, is_active, is_approved, image_id, category_id) VALUES ({$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y', 'Y', {$image_id}, {$category_id});";
			$this->query($album_assign_sql);
		}

		#echo "Registering: {$image_file} - Image ID: {$image_id}, Album ID: {$album_id}, Category ID: {$category_id}"; die;

		return $image_id;
	}
	
	
	/**
	* Counts the impressions - from the details/public page
	*/
	public function count_impressions($image_id=0, $protection_code='')
	{
		$image_id = (int)$image_id;
		$protection_code = $this->sanitize($protection_code);
		$count_impressions_sql="
UPDATE gallery_images SET
	impressions_counter=impressions_counter+1
WHERE
	image_id={$image_id}
	AND MD5(CONCAT(`image_id`, '{$this->protection_code}'))='{$protection_code}'
;";
		return $this->query($count_impressions_sql);
	}
	
	/**
	* Verifies images
	*/
	public function verify_image($image_id=0, $album_details=array())
	{
		die('No verification at the moment. Thumbnails are created elsewhere. Also, please pass size ID.');
		$unapproved = false;
		$image = $this->details($image_id);
		if(!$image)
		{
			# Do other things to remove the record...
			$unapproved = true;
			
			# setup a blank image details to NOT to frustrate the below code
			$image = array(
				'image_name' => null,
				'album_folder' => null,
			);
		}
		#print_r($image);
		
		/*
		$image_file = "{$album_details['album_folder']}/{$image['image_name']}";
		$thumbnail_file = "{$album_details['album_folder']}/thumbnails/{$image['image_name']}";
		#$thumbnail_file = FTPPATH_THUMBNAILS."/{$album_details['album_id']}/thumbnails/{$image['image_name']}";
		#die($thumbnail_file.', '.realpath($image_file));
		if(!is_file(realpath($image_file)))
		{
			# Captured, the image does not exist
			# Patch invalid
			$this->query("UPDATE gallery_images SET is_approved='N' WHERE image_id={$image_id};");
			$this->query("UPDATE gallery_images_albums SET is_approved='N' WHERE image_id={$image_id} AND album_id={$album_details['album_id']};");
			
			$unapproved = true;
		}
		else
		*/
		{
			$this->query("UPDATE gallery_images SET is_approved='Y' WHERE image_id={$image_id};");
			$this->query("UPDATE gallery_images_albums SET is_approved='Y', fixed_on=UNIX_TIMESTAMP(CURRENT_TIMESTAMP()) WHERE image_id={$image_id} AND album_id={$album_details['album_id']};");
			
			#touch($image_file);
			
			$sizes = $this->arrays("
SELECT size_id, dimension_width, dimension_height
FROM gallery_sizes
WHERE
	is_active='Y'
	AND is_approved='Y'
	AND dimension_width > 0
	AND dimension_height > 0
;");
			#print_r($sizes); die();
			foreach($sizes as $s => $size)
			{
				#$thumbnail_file = "{$album_details['album_folder']}/thumbnails/{$size['size_id']}/{$image['image_name']}";
				$thumbnail_file = FTPPATH_THUMBNAILS."{$size['size_id']}/{$image['image_id']}.jpg";
				
				/*
				# Check for the thumbnails or create them now.
				#die('Checking thumbnail: '.$thumbnail_file);
				if(!is_file($thumbnail_file))
				{
					if(!is_dir(dirname($thumbnail_file)))
					{
						mkdir(dirname($thumbnail_file), 0777, true);
					}
					
					# Make all the thumbmails
					#print_r($size);
					$thumbnailer = new thumbnailer($image_file);
					$thumbnailer->generate($new_width=$size['dimension_width'], $new_height=$size['dimension_height'], $thumbnail_file, $quality=75);
					*/
				} # foreach
			} # if/else
			#print_r($sizes); die();
			
			
			#die($thumbnail_file);
		#}
		
		return $unapproved;
	
		#print_r($album_details);
		#die;
/*
Array
(
    [image_id] => 2
    [subdomain_id] => 71
    [checked_on] => 0
    [added_on] => 1326830559
    [fixed_on] => 0
    [modified_on] => 0
    [modified_counter] => 0
    [sink_weight] => 0
    [is_active] => Y
    [is_approved] => N
    [is_valid] => N
    [dimension_width] => 180
    [dimension_height] => 540
    [filesize_bytes] => 20591
    [impressions_counter] => 0
    [votes_counter] => 0
    [downloads_counter] => 0
    [image_code] => 201201180147398928
    [image_name] => 369727_1601757661_2066078439_n.jpg
    [image_mime] => 
    [image_hash] => 1600f0329fce27ac1f534e84b9758758150b3801
    [image_caption] => 
    [image_keywords] => 
    [image_description] => 
    [code] => 7f8e4bd9ad86eae3dcb36ee33a0e7c92
)
Array
(
    [album_id] => 8
    [subdomain_id] => 71
    [added_on] => 1326828121
    [fixed_on] => 0
    [modified_on] => 0
    [modified_counter] => 0
    [images_counter] => 10
    [sink_weight] => 0
    [is_active] => Y
    [is_approved] => N
    [album_name] => other-pics
    [album_folder] => F:/Desktop/other-pics
    [album_folder_local] => 
    [album_coverimage] => 
    [album_description] => 
    [code] => 087a1a1e66c0631d1a988101983923d4
)*/
	}
	
	/**
	* Check the validity of the image
	* Album should be active
	* Image should be active
	*/
	public function is_valid($image_id=0, $protection_code='')
	{
		$image_id = (int)$image_id;
		$protection_code = $this->sanitize($protection_code);
		
		# When admin has logged in, validate.
		if(isset($_SESSION['is_admin']) && $_SESSION['is_admin']==true) return true;
		
		$is_valid=false;
		
		if($image = $this->details($image_id))
		{
			if($image['is_active']=='Y' && $image['is_approved']=='Y')
			{
				$check_album_sql="
SELECT
	a.album_id,
	ia.image_id
FROM gallery_images_albums ia
INNER JOIN gallery_albums a ON
	a.album_id = ia.album_id
	AND ia.is_active='Y'
	AND ia.is_approved='Y'
	AND a.is_active='Y'
	AND a.is_approved='Y'
;";
				$album = $this->row($check_album_sql);
				#print_r($album); die($check_album_sql);
				if(isset($album['album_id']) && $album['album_id'])
				{
					$is_valid=true;
				}
			}
		}
		if($is_valid!=true)
		{
			# Counts invlid access attempts
			$invalid_counter_sql = "UPDATE gallery_images SET invalid_counter=invalid_counter+1 WHERE image_id={$image_id};";
			$this->query($invalid_counter_sql);
		}
		
		return $is_valid;
	}
	
	
	/**
	* Find out album ID of an image
	*/
	public function album_id($image_id=0)
	{
		$image_id = (int)$image_id;
		$album_id_sql="SELECT album_id FROM gallery_images_albums WHERE image_id={$image_id};";
		$album = $this->row($album_id_sql);
		
		if(!isset($album['album_id'])) $album = array('album_id' => 0);
		return $album['album_id'];
	}
	
	/**
	* Checks if the image is valid to server or not
	*/
	public function is_valid_image($image_id=0)
	{
		$image_id = (int)$image_id;
		
		$check_image_sql="
SELECT
	image_id
FROM gallery_images
WHERE
	image_id={$image_id}
	
	AND is_active='Y'
	AND is_approved='Y'

	# Optionally validate the image dates, publication, expiry, private images etc
;";
		#die($check_image_sql);
		$image = $this->row($check_image_sql);
		if(!isset($image['image_id'])) $image = array('image_id' => 0);
		return $image['image_id'];
	}
	
	/**
	* Read out the base name of the image scanned originally
	*/
	public function base_name($image_id=0)
	{
		$image_id = (int)$image_id;
		$base_name_sql="SELECT image_name FROM gallery_images WHERE image_id={$image_id};";
		$base_name = $this->row($base_name_sql);
		
		if(!isset($base_name['image_name'])) $base_name = array('image_name' => '');
		return $base_name['image_name'];
	}
	
	/**
	* Navigate to the previous/next image of the album
	*/
	function navigate_id($image_id=0, $action='none')
	{
		$image_id = (int)$image_id;
		$action = in_array($action, array('previous', 'next'))?$action:none;
		
		# simulation only
		$image_id = ($action=='previous')?$image_id-1:$image_id+1;
		return $image_id;
	}
}
?>